<template>
  <div class="syncOrder">
    <Button type="primary" :disabled="!buttonAuth" @click="clickHandle">同步工单</Button>
    <el-dialog
      :visible.sync="visible"
      destroy-on-close
      width="60%"
      :close-on-click-modal="false"
      title="同步工单"
      :append-to-body="true"
      @open="openHandle"
      @close="resetHandle"
    >
      <div class="contentBody">
        <el-form
          ref="form"
          :model="formData"
          :rules="formRules"
          inline
          label-width="80px"
        >
          <el-row>
            <el-col :span="18">
              <el-form-item prop="workOrderCode" label="工单编号">
                <el-input
                  v-model="formData.workOrderCode"
                  placeholder="请输入工单编号"
                  clearable
                  @input="clearDetail"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <div>
                  <Button type="primary" :loading="isLoading" @click="queryHandle">查询</Button>
                  <Button v-if="showDetail" type="primary" :loading="submitLoading" @click="submitHandle">确认</Button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div v-loading="isLoading" element-loading-text="数据加载中" class="list">
          <List :column="3" :gutter="20" sep="：" label-width="85px" align="right">
            <ListItem label="工单编号" :value="detail.workOrderCode" />
            <ListItem label="工单状态" dict-type-code="WORK_ORDER_STATUS" :value="detail.workOrderState" />
            <ListItem label="创建时间" :value="detail.createTime ? detail.createTime : '--'" />
            <ListItem label="创建人" :value="detail.createrName?`${detail.createrName}(${detail.createBy})${detail.createByPlatformNo?' - ' + detail.createByPlatformNo:''}`:''" />
            <!-- <ListItem label="创建人" :value="`${detail.createrName ? detail.createrName : ''}(${detail.createBy ? detail.createBy : ''})`" /> -->
            <ListItem label="联系渠道" :value="detail.channelTypeName ? detail.channelTypeName : '--'" />
            <ListItem label="一级业务类型" :value="detail.businessType1Name ? detail.businessType1Name : '--'" />
            <ListItem label="二级业务类型" :value="detail.businessType2Name ? detail.businessType2Name : '--'" />
            <ListItem label="责任部门" :value="detail.bpmDeptName ? detail.bpmDeptName : '--'" />
            <ListItem label="联系人" :value="detail.contactName" />
            <ListItem label="联系电话" :value="detail.contactPhone" />
            <ListItem label="顾客ID" :value="detail.nickname ? detail.nickname : '--'" />
            <ListItem label="平台订单号" :value="detail.orderCode" />
            <ListItem label="电商单号" :value="detail.ecOrderNumber" />
            <ListItem label="产品类型" :value="detail.productTypeName" />
            <ListItem label="功能空间" :value="detail.functionalSpaceName" />
            <ListItem label="产品品类" :value="detail.productCategoryName" />
            <ListItem label="产品型号" :value="detail.productMode" />
            <ListItem label="办事处" :value="detail.officeName" />
            <ListItem label="经销商" :value="detail.disName" :span="24" />
            <ListItem label="门店" :span="24" :value="detail.shopName" />
            <ListItem label="售后电话" :value="detail.afterSalesCall" />
            <ListItem label="紧急程度" :value="detail.urgencyDegreeName" />
            <ListItem label="来电明细" :span="24" :value="detail.callContent" />
            <ListItem label="客服意见" :span="24" :value="detail.customerServiceOpinion" />
          </List>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { List, ListItem } from '@/components/List'
import Button from '@/components/Button'
import { getBusinessDeptRelByCode } from '@/api/BusinessDeptRel'
import { postSyncWorkOrder, getWorkOrderByCode } from '@/api/workOrder'
export default {
  name: 'SyncOrder',
  components: {
    List,
    ListItem,
    Button
  },
  props: {
    callContent: {
      type: String,
      default: ''
    },
    customer: {
      type: String,
      default: ''
    },
    enableOpen: {
      type: Function,
      default: () => Promise.reject(),
      require: true
    },
    buttonAuth: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isLoading: false,
      visible: false,
      formData: {
        workOrderCode: ''
      },
      formRules: {
        workOrderCode: [
          { required: true, message: '请输入工单号', trigger: 'change' }
        ]
      },
      detail: {},
      submitLoading: false
    }
  },
  computed: {
    showDetail() {
      return Object.keys(this.detail).length > 0
    },
    isVaild() {
      if (!this.callContent || !this.customer) {
        return false
      }
      return true
    }
  },
  methods: {
    openHandle() {
    },
    clickHandle() {
      this.enableOpen().then(() => {
        this.visible = true
      })
    },
    // 输入框值改变时
    clearDetail() {
      // this.detail = {}
    },
    // 查询订单详细
    queryHandle() {
      const _this = this
      _this.$refs.form.validate().then(() => {
        // FIXME:根据实际情况改
        _this.isLoading = true
        const { workOrderCode } = _this.formData
        getWorkOrderByCode(workOrderCode).then(async(response) => {
          if (response.success === 1) {
            const data = { ...response.data }
            data.bpmDeptName = await _this.$getDictValue('RESPONSIBLE_DEPARTMENT', data.bpmDeptCode)
            data.channelTypeName = await _this.$getDictValue('CHANNEL_TYPE', data.channelType)
            data.productTypeName = await _this.$getDictValue('PRODUCT_TYPE', data.productType)
            data.functionalSpaceName = await _this.$getDictValue('FUNCTIONAL_SPACE', data.functionalSpace)
            data.productCategoryName = await _this.$getDictValue('PRODUCT_CATEGORY', data.productCategory)
            data.urgencyDegreeName = await _this.$getDictValue('URGENCY_DEGREE', data.urgencyDegree)
            data.overdueReasonName = await _this.$getDictValue('OVERDUE_REASON', data.overdueReason)
            data.timeoutReasonName = await _this.$getDictValue('TIMEOUT_REASON', data.timeoutReason)
            data.businessType1Name = await _this.findBusinessTypeName(0, data.businessType1)
            data.businessType2Name = await _this.findBusinessTypeName(data.businessType1, data.businessType2)
            _this.detail = data
            _this.$nextTick(() => {
              _this.isLoading = false
            })
            return
          }
          _this.isLoading = false
        }, () => {
          _this.isLoading = false
        })
      })
    },
    // 确认
    submitHandle() {
      // FIXME:根据实际情况修改
      if (!this.isVaild) {
        this.$message({
          message: '来电明细及客服意见不能为空',
          type: 'error'
        })
        this.visible = false
        return
      }
      const { id } = this.detail
      const { organization, accountNo, staffName } = this.$store.state.user.userCache
      const params = {
        workOrderId: id,
        content: `来电明细：${this.callContent}；客服意见：${this.customer}`
      }
      if (accountNo) params.handler = accountNo
      if (staffName) params.handlerName = staffName
      if (organization) params.deptName = organization

      this.$msgbox({
        title: '同步工单',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        message: '确定同步工单?',
        type: 'warning'
      }).then(() => {
        this.submitLoading = true
        return postSyncWorkOrder(params).then(res => {
          if (res.success === 1) {
            this.$message({
              message: '工单同步成功',
              type: 'success'
            })
            this.$emit('on-success', true)
            this.$nextTick(() => {
              this.visible = false
            })
          }
        }).finally(() => {
          this.submitLoading = false
        })
      })
    },
    // 重置组件
    resetHandle() {
      this.$refs.form.resetFields()
      this.detail = {}
    },
    // 业务类型
    findBusinessTypeName(parentCode, busiCode) {
      return getBusinessDeptRelByCode(parentCode)
        .then(res => {
          if (res.success === 1) {
            for (const list of res.data) {
              if (Number(list.relationCode) === Number(busiCode)) {
                return list.relationName ? list.relationName : '--'
              }
            }
          }
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.syncOrder {
  display: inline-block;
  .contentBody {
    margin: -10px;
    .list {
      padding: 10px;
    }
  }
}
.contentBody /deep/ .el-row .el-col {
  line-height: 32px;
}
.contentBody /deep/ .el-row .custom-list-item {
  margin-bottom: 0;
}
.contentBody /deep/ .el-row .custom-list-item .label-style {
  text-align-last: right;
}
.contentBody /deep/ .el-row .el-form-item {
  width: 100%;
}
.contentBody /deep/ .el-row .el-form-item .el-form-item__content {
  width: 80%;
}
.contentBody /deep/ .el-row .custom-list-item span:first-child {
  width: 90px;
  font-size: 13px;
  text-align: right;
}
.contentBody /deep/ .el-row .custom-list-item span:last-child {
  font-size: 12px;
}
</style>
